package com.baozi.product.controller;

import com.baozi.product.DTO.CartDto;
import com.baozi.product.entity.ProductCategory;
import com.baozi.product.entity.product;
import com.baozi.product.service.ProductCategoryService;
import com.baozi.product.service.productService;
import com.baozi.product.vo.ProductInfoVo;
import com.baozi.product.vo.ProductVo;
import com.baozi.product.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("products")
public class ProductController {

    @Autowired
    private productService service;

    @Autowired
    private ProductCategoryService productCategoryService;

    @GetMapping("list")
    public ResultVo<ProductVo> list(){
        //获取所有商品
        List<product> list=service.findUpAll();
        //获取商品所有类型
        List<Integer> list2=list.stream()
                            .map(product::getCategoryType)
                            .collect(Collectors.toList());
        //查询所有类目
        List<ProductCategory> list3=productCategoryService.findByCategoryTypeIn(list2);
        //构造数据
        List<ProductVo> list4=new ArrayList<>();
        for(ProductCategory arr:list3){
            ProductVo vo=new ProductVo();
            vo.setCategoryName(arr.getCategoryName());
            vo.setCategoryType(arr.getCategoryType());
            List<ProductInfoVo> productInfoVoList=new ArrayList<>();
            for(product pt:list){
                if(pt.getCategoryType().equals(arr.getCategoryType())) {
                    ProductInfoVo infoVo = new ProductInfoVo();
                    BeanUtils.copyProperties(pt, infoVo);
                    productInfoVoList.add(infoVo);
                }
            }
            vo.setProductInfoVoList(productInfoVoList);
            list4.add(vo);
        }

        ResultVo voo=new ResultVo();
        voo.setCode(0);
        voo.setMsg("11");
        voo.setData(list4);

        return voo;
     }

    /**
     * 获取商品列表给order用的，通过feign
     * @param productList
     * @return
     */
    @PostMapping("listForOrder")
    public List<product> list(@RequestBody  List<String> productList){
        return service.list(productList);
    }

    @PostMapping("deleteStocke")
    public void deleteStocke(@RequestBody List<CartDto> list){
        service.deleteStock(list);
    }

}
